Popular Searches
Popular Course Categories
Popular Courses

Working with Arithmetic Operators

Working with Arithmetic Operators

Operators and Expressions in Java

Working with Arithmetic Operators in Java

Course: Core Java Training

Topic: Working with Arithmetic Operators

Course Link: Core Java Training Course

Demo Link: Register for a Free Course Demo

Academy Website: JustAcademy


1. Introduction to Arithmetic Operators in Java

Arithmetic operators in Java are symbols used to perform mathematical calculations on numeric values and variables. They are essential for calculations involving totals, averages, prices, percentages, measurements, counters, and many other programming tasks.

Java supports common arithmetic operations such as addition, subtraction, multiplication, division, and remainder calculation. It also provides unary operators, including increment and decrement, for modifying numeric values.

For example, the expression int total = 10 + 5; uses the addition operator (+) to calculate the sum of two numbers and stores the result in the variable total.

Learning Objectives

  • Understand the purpose of arithmetic operators in Java.
  • Learn how to use addition, subtraction, multiplication, division, and modulus operators.
  • Understand unary plus, unary minus, increment, and decrement operators.
  • Distinguish between integer division and floating-point division.
  • Understand operator precedence and associativity.
  • Identify common arithmetic errors and apply best practices.

2. Types of Arithmetic Operators

Java provides the following commonly used arithmetic operators:

Operator Name Example Result
+ Addition 10 + 3 13
- Subtraction 10 - 3 7
* Multiplication 10 * 3 30
/ Division 10 / 3 3 when both operands are integers
% Remainder (modulus) 10 % 3 1
+ Unary plus +5 5
- Unary minus -5 -5
++ Increment x++ Increases x by 1
-- Decrement x-- Decreases x by 1

3. Addition Operator (+)

The addition operator adds two numeric operands. The result depends on the types of the operands and the type of the expression.

Example

public class AdditionExample {
    public static void main(String[] args) {
        int a = 20;
        int b = 15;
        int sum = a + b;

        System.out.println("First number: " + a);
        System.out.println("Second number: " + b);
        System.out.println("Sum: " + sum);
    }
}

Output:

First number: 20
Second number: 15
Sum: 35

How It Works

  1. The variables a and b store the values 20 and 15.
  2. The expression a + b adds both values.
  3. The result, 35, is stored in sum.
  4. The println() statements display the values.

Practical Example: Calculating a Total Price

public class TotalPrice {
    public static void main(String[] args) {
        double item1 = 149.50;
        double item2 = 250.00;
        double total = item1 + item2;

        System.out.println("Total price: " + total);
    }
}

Output:

Total price: 399.5

Java's + operator also concatenates strings. For example, "Total: " + 35 produces the string "Total: 35". When strings and numbers are mixed in one expression, evaluation order affects the result.

System.out.println("Result: " + 10 + 5);
System.out.println("Result: " + (10 + 5));

Output:

Result: 105
Result: 15

In the first statement, string concatenation occurs from left to right. In the second, parentheses cause the numeric addition to happen first.

4. Subtraction Operator (-)

The subtraction operator subtracts the right operand from the left operand. It can be used with integer and floating-point values.

Example

public class SubtractionExample {
    public static void main(String[] args) {
        int totalMarks = 100;
        int marksObtained = 78;
        int remainingMarks = totalMarks - marksObtained;

        System.out.println("Remaining marks: " + remainingMarks);
    }
}

Output:

Remaining marks: 22

Practical Uses

  • Calculating the remaining balance in a bank account.
  • Finding the difference between two measurements.
  • Calculating discounts and remaining quantities.
  • Determining the time or distance between two values.

Example: Remaining Account Balance

double balance = 5000.00;
double withdrawal = 1250.00;
double remainingBalance = balance - withdrawal;

System.out.println("Remaining balance: " + remainingBalance);

Output:

Remaining balance: 3750.0

5. Multiplication Operator (*)

The multiplication operator multiplies two numeric values. It is useful for calculating totals based on quantity, repeated costs, areas, and other mathematical operations.

Example

public class MultiplicationExample {
    public static void main(String[] args) {
        int price = 120;
        int quantity = 4;
        int totalCost = price * quantity;

        System.out.println("Total cost: " + totalCost);
    }
}

Output:

Total cost: 480

Example: Calculating Rectangle Area

public class RectangleArea {
    public static void main(String[] args) {
        double length = 12.5;
        double width = 4.0;
        double area = length * width;

        System.out.println("Rectangle area: " + area);
    }
}

Output:

Rectangle area: 50.0

Important: Multiplying integer values can cause integer overflow if the mathematical result exceeds the range of the data type. For example, a multiplication involving large int values may wrap around instead of producing the expected mathematical result. Use an appropriately sized type, such as long, and convert operands before multiplication when necessary.

int a = 100000;
int b = 100000;
long result = (long) a * b;

System.out.println(result);

Output:

10000000000

Casting only the final result, as in (long) (a * b), would be too late if the multiplication already overflowed as an int. Cast an operand before the operation.

6. Division Operator (/)

The division operator divides the left operand by the right operand. The type of the operands determines how Java calculates the result.

Integer Division

When both operands are integer types, Java performs integer division. Any fractional part is discarded, meaning the result is truncated toward zero.

public class IntegerDivision {
    public static void main(String[] args) {
        int a = 10;
        int b = 3;

        System.out.println(a / b);
        System.out.println(-10 / 3);
    }
}

Output:

3
-3

The mathematical result of 10 divided by 3 is approximately 3.333, but integer division returns 3. Negative integer division also truncates toward zero rather than rounding down.

Floating-Point Division

When at least one operand is a float or double, Java performs floating-point division.

public class FloatingPointDivision {
    public static void main(String[] args) {
        double a = 10.0;
        double b = 3.0;

        System.out.println(a / b);
    }
}

Output:

3.3333333333333335

Floating-point results are approximations for many decimal fractions, so the displayed result may contain more digits than expected.

Converting Integer Division to Decimal Division

int total = 7;
int count = 2;

double wrongAverage = total / count;
double correctAverage = (double) total / count;

System.out.println(wrongAverage);
System.out.println(correctAverage);

Output:

3.0
3.5

In the first calculation, total / count is evaluated as integer division before being assigned to a double. Casting one operand before division makes the operation use floating-point arithmetic.

Division by Zero

Division by zero requires special attention:

  • Integer division by zero, such as 10 / 0, throws an ArithmeticException.
  • Floating-point division by zero generally produces positive or negative infinity, depending on the operands.
  • Floating-point 0.0 / 0.0 produces NaN (Not a Number).
int divisor = 0;

// Check before performing integer division.
if (divisor != 0) {
    System.out.println(10 / divisor);
} else {
    System.out.println("Division by zero is not allowed.");
}

Output:

Division by zero is not allowed.

7. Modulus Operator (%)

The modulus operator, written as %, returns the remainder after division. It is commonly used to determine whether a number is even or odd, check divisibility, and repeat actions at regular intervals.

Example

public class ModulusExample {
    public static void main(String[] args) {
        int a = 17;
        int b = 5;

        System.out.println("Quotient: " + (a / b));
        System.out.println("Remainder: " + (a % b));
    }
}

Output:

Quotient: 3
Remainder: 2

Since 5 fits into 17 three times, 15 is accounted for and 2 remains.

Checking Even and Odd Numbers

public class EvenOdd {
    public static void main(String[] args) {
        int number = 14;

        if (number % 2 == 0) {
            System.out.println("Even number");
        } else {
            System.out.println("Odd number");
        }
    }
}

Output:

Even number

An integer is even when its remainder after division by 2 is zero. Otherwise, it is odd.

Checking Divisibility

int number = 30;

if (number % 5 == 0) {
    System.out.println("Divisible by 5");
}

Output:

Divisible by 5

Negative Remainders

In Java, the sign of a nonzero remainder follows the sign of the dividend (the left operand).

System.out.println(10 % 3);
System.out.println(-10 % 3);
System.out.println(10 % -3);
System.out.println(-10 % -3);

Output:

1
-1
1
-1

For a nonnegative remainder in a known positive range, Math.floorMod() may be more suitable, especially when working with cyclic indexes or negative inputs.

8. Unary Plus (+) and Unary Minus (-)

Unary arithmetic operators act on a single operand. Unary plus indicates a positive value and usually leaves the numeric value unchanged. Unary minus negates the operand.

Example

public class UnaryOperators {
    public static void main(String[] args) {
        int a = 8;
        int b = -a;
        int c = +a;

        System.out.println("Original: " + a);
        System.out.println("Unary minus: " + b);
        System.out.println("Unary plus: " + c);
    }
}

Output:

Original: 8
Unary minus: -8
Unary plus: 8

Unary minus does not change the value stored in a; it creates a negated expression result. If you want to update the variable, assign the result back to it, such as a = -a;.

9. Increment Operator (++)

The increment operator increases a numeric variable by one. Java supports two forms: pre-increment (++x) and post-increment (x++).

Pre-Increment

Pre-increment increases the variable first and then evaluates to the updated value.

int x = 5;
int result = ++x;

System.out.println("x = " + x);
System.out.println("result = " + result);

Output:

x = 6
result = 6

Post-Increment

Post-increment evaluates to the original value and then increases the variable by one.

int x = 5;
int result = x++;

System.out.println("x = " + x);
System.out.println("result = " + result);

Output:

x = 6
result = 5

Difference Between Pre-Increment and Post-Increment

Expression Initial Value of x Value Assigned to result Final Value of x
result = ++x; 5 6 6
result = x++; 5 5 6

When incrementing a variable by one without using its value in another expression, both forms produce the same final variable value:

x++;
++x;

For readability, avoid placing multiple increment or decrement operations in a complicated expression.

10. Decrement Operator (--)

The decrement operator decreases a numeric variable by one. Like increment, it has pre-decrement (--x) and post-decrement (x--) forms.

Example

public class DecrementExample {
    public static void main(String[] args) {
        int x = 10;

        System.out.println(--x);
        System.out.println(x--);
        System.out.println(x);
    }
}

Output:

9
9
8

Explanation

  1. --x reduces x from 10 to 9 and returns 9.
  2. x-- returns the current value 9 and then reduces x to 8.
  3. The final statement prints the updated value, 8.

11. Compound Arithmetic Assignment Operators

Java provides compound assignment operators that combine an arithmetic operation with assignment. They are useful for updating a variable in a concise way.

Operator Equivalent Form Example (x starts at 10) New Value of x
+= x = x + 5; x += 5; 15
-= x = x - 3; x -= 3; 7
*= x = x * 2; x *= 2; 20
/= x = x / 2; x /= 2; 5
%= x = x % 3; x %= 3; 1

Example Program

public class CompoundAssignment {
    public static void main(String[] args) {
        int score = 50;

        score += 10;
        System.out.println("After addition: " + score);

        score -= 5;
        System.out.println("After subtraction: " + score);

        score *= 2;
        System.out.println("After multiplication: " + score);

        score /= 5;
        System.out.println("After division: " + score);

        score %= 7;
        System.out.println("After modulus: " + score);
    }
}

Output:

After addition: 60
After subtraction: 55
After multiplication: 110
After division: 22
After modulus: 1

Note: Compound assignment includes an implicit conversion back to the left-hand variable's type. For example, short value = 10; value += 2; is valid, while value = value + 2; requires an explicit cast because the addition is evaluated as an int.

12. Arithmetic Operator Precedence

When an expression contains multiple operators, Java follows operator precedence rules to determine the order of evaluation. Parentheses can be used to make the intended order explicit.

For the common arithmetic operators, the general order from higher to lower precedence is:

  1. Parenthesized expressions, evaluated according to their contents.
  2. Unary operators such as ++, --, unary +, and unary -.
  3. Multiplication, division, and remainder: *, /, %.
  4. Addition and subtraction: +, -.
  5. Assignment operators such as = and compound assignments.

Example Without Parentheses

int result = 10 + 5 * 2;
System.out.println(result);

Output:

20

Multiplication is performed before addition: 5 × 2 = 10, then 10 + 10 = 20.

Example With Parentheses

int result = (10 + 5) * 2;
System.out.println(result);

Output:

30

The parentheses cause addition to occur first: 10 + 5 = 15, then 15 × 2 = 30.

13. Operator Associativity

Operator precedence determines which operator has priority. Associativity determines the evaluation grouping when operators of the same precedence appear together.

Most binary arithmetic operators, such as +, -, *, /, and %, group from left to right.

int result = 20 / 5 * 2;
System.out.println(result);

Output:

8

The expression is grouped as (20 / 5) * 2, producing 4 × 2 = 8. It is not grouped as 20 / (5 * 2).

Assignment operators group from right to left, so an expression such as a = b = 10; assigns 10 to b and then to a.

14. Data Types and Arithmetic Results

The operand types influence the result of an arithmetic expression. Understanding numeric promotion helps prevent unexpected values and compilation errors.

Operand Types Typical Arithmetic Result Type Important Detail
byte, short, char int for arithmetic operations These types are promoted to at least int.
int and int int Division truncates the fractional part.
long with integer operands Usually long Results can still overflow the range of long.
Any arithmetic involving float Usually float, unless a double is involved Precision is lower than double.
Any arithmetic involving double double Decimal values may be represented approximately.

Example: Numeric Promotion

byte a = 10;
byte b = 20;
int result = a + b;

System.out.println(result);

Output:

30

Even though both operands are declared as byte, the addition expression is evaluated as an int. Therefore, the result is stored in an int.

15. Floating-Point Precision and Financial Calculations

Java's float and double types use binary floating-point representation. Many decimal fractions cannot be represented exactly in binary, which can lead to small rounding differences.

public class PrecisionExample {
    public static void main(String[] args) {
        double result = 0.1 + 0.2;
        System.out.println(result);
    }
}

Typical output:

0.30000000000000004

This behavior is normal for binary floating-point arithmetic. It is not necessarily a Java bug.

For financial calculations requiring decimal precision, consider using BigDecimal with an appropriate rounding policy.

import java.math.BigDecimal;
import java.math.RoundingMode;

public class MoneyExample {
    public static void main(String[] args) {
        BigDecimal price = new BigDecimal("19.99");
        BigDecimal quantity = new BigDecimal("3");
        BigDecimal total = price.multiply(quantity);

        BigDecimal rounded = total.setScale(2, RoundingMode.HALF_UP);
        System.out.println("Total: " + rounded);
    }
}

Output:

Total: 59.97

Construct BigDecimal from decimal strings when exact decimal input matters. Creating it from a double may preserve the double's existing binary approximation.

16. Common Mistakes When Using Arithmetic Operators

Mistake Why It Happens Recommended Solution
Expecting 10 / 3 to return 3.333 Both operands are integers. Use 10.0 / 3 or cast an operand to double.
Dividing an integer by zero The divisor has the value zero. Validate the divisor before integer division.
Using + and strings without considering order String concatenation and arithmetic are different operations. Use parentheses around calculations.
Confusing x++ with ++x The expressions return different values. Use separate statements when clarity matters.
Assuming floating-point values are exact decimals Binary floating-point cannot represent many decimal fractions exactly. Use a suitable comparison strategy or BigDecimal for decimal arithmetic.
Ignoring integer overflow The result exceeds the range of the numeric type. Choose an appropriate type and check bounds where needed.
Using an incorrect operator order Precedence may differ from the intended formula. Use parentheses to make calculations explicit.

17. Practical Program: Simple Calculator

The following program demonstrates addition, subtraction, multiplication, division, and remainder using two integer values.

public class SimpleCalculator {
    public static void main(String[] args) {
        int first = 20;
        int second = 6;

        System.out.println("Addition: " + (first + second));
        System.out.println("Subtraction: " + (first - second));
        System.out.println("Multiplication: " + (first * second));
        System.out.println("Integer division: " + (first / second));
        System.out.println("Remainder: " + (first % second));

        if (second != 0) {
            System.out.println("Decimal division: "
                    + ((double) first / second));
        } else {
            System.out.println("Cannot divide by zero.");
        }
    }
}

Output:

Addition: 26
Subtraction: 14
Multiplication: 120
Integer division: 3
Remainder: 2
Decimal division: 3.3333333333333335

Program Explanation

  1. Two integer variables, first and second, store the input values.
  2. Each arithmetic operator performs a different calculation on those values.
  3. Parentheses ensure that the arithmetic calculation happens before string concatenation.
  4. The division result is checked using a condition to prevent integer division by zero.
  5. Casting first to double allows decimal division.

18. Practical Program: Calculate the Average of Three Numbers

Calculating an average is a common application of addition and division. The values should be added first, and the sum should then be divided by the number of values.

public class AverageCalculator {
    public static void main(String[] args) {
        int mark1 = 85;
        int mark2 = 90;
        int mark3 = 78;

        int total = mark1 + mark2 + mark3;
        double average = total / 3.0;

        System.out.println("Total marks: " + total);
        System.out.println("Average marks: " + average);
    }
}

Output:

Total marks: 253
Average marks: 84.33333333333333

The divisor 3.0 ensures floating-point division. If the program used total / 3, integer division would discard the fractional part before assigning the result to the double variable.

19. Best Practices for Arithmetic Operations

  • Choose suitable data types: Use int for ordinary whole-number calculations, long for larger integer ranges, and floating-point types for approximate decimal calculations.
  • Prevent division by zero: Validate integer divisors before performing division or remainder operations.
  • Use parentheses: Make complex expressions easier to understand and reduce precedence-related mistakes.
  • Handle overflow: Consider maximum and minimum values when working with large numbers. Methods such as Math.addExact() and Math.multiplyExact() can throw an exception when integer overflow occurs.
  • Be careful with floating-point equality: For approximate calculations, compare values using a suitable tolerance rather than assuming exact equality.
  • Use BigDecimal for precise decimal arithmetic: This is often appropriate for monetary values, with a clearly defined rounding strategy.
  • Avoid complicated increment expressions: Use separate statements to make the order of changes clear.
  • Use meaningful variable names: Names such as totalPrice, remainingBalance, and averageMarks communicate the purpose of calculations.
  • Test boundary values: Check zero, negative numbers, large values, and values near the limits of the selected data type.

20. Exercises for Practice

Beginner Exercises

  1. Write a program that adds two integers and displays the sum.
  2. Write a program that calculates the difference between a product's marked price and its selling price.
  3. Calculate the total cost of an item using its unit price and quantity.
  4. Divide two integers and display both the quotient and the remainder.
  5. Write a program that checks whether a given integer is even or odd using the modulus operator.

Intermediate Exercises

  1. Calculate the average of five subject marks using floating-point division.
  2. Demonstrate the difference between pre-increment and post-increment.
  3. Use compound assignment operators to update a bank balance.
  4. Write an expression that calculates the area of a circle using a radius and Math.PI.
  5. Write a calculator that handles division by zero safely.

Challenge Exercise: Shopping Bill

Create a Java program that calculates a shopping bill using arithmetic operators. Store the unit price and quantity of three products, calculate each line total, add the line totals, apply a discount, and display the final amount.

Requirements:

  • Use meaningful variable names.
  • Use multiplication to calculate each product's total.
  • Use addition to calculate the subtotal.
  • Use arithmetic operations to calculate the discount and final amount.
  • Use BigDecimal if you want to practice accurate decimal monetary calculations.

21. Interview Questions and Answers

Q1. What are arithmetic operators in Java?

Answer: Arithmetic operators are symbols used to perform mathematical calculations. Common examples include addition (+), subtraction (-), multiplication (*), division (/), and remainder (%).

Q2. What is the difference between division and modulus?

Answer: Division calculates the quotient, while modulus returns the remainder. For example, 17 / 5 returns 3 with integer operands, whereas 17 % 5 returns 2.

Q3. Why does 10 / 3 return 3 instead of 3.333?

Answer: Both operands are integers, so Java performs integer division and truncates the fractional part toward zero. Using 10.0 / 3 produces a floating-point result.

Q4. What is the difference between ++x and x++?

Answer: Pre-increment increases the variable before the expression's value is evaluated. Post-increment evaluates to the original value and then increases the variable.

Q5. What happens when an integer is divided by zero?

Answer: Java throws an ArithmeticException when an integer division or remainder operation has a zero divisor.

Q6. What is operator precedence?

Answer: Operator precedence defines which operators are evaluated first in an expression. Multiplication, division, and remainder generally have higher precedence than addition and subtraction.

Q7. What is integer overflow?

Answer: Integer overflow occurs when an arithmetic result exceeds the minimum or maximum value supported by an integer type. Java integer arithmetic generally wraps around rather than automatically raising an overflow exception.

Q8. Can the plus operator be used for string concatenation?

Answer: Yes. When one operand is a string, the plus operator can concatenate string representations. Parentheses can be used to ensure numeric calculations happen before concatenation.

Q9. Why can 0.1 + 0.2 produce an unexpected decimal result?

Answer: The double type uses binary floating-point representation, which cannot represent many decimal fractions exactly. Small rounding differences can occur.

Q10. Which Java class is useful for precise decimal calculations?

Answer: BigDecimal is useful for decimal calculations that require explicit precision and rounding, including many financial applications.

22. Quick Revision Checklist

  • Addition uses +.
  • Subtraction uses -.
  • Multiplication uses *.
  • Division uses /.
  • Remainder uses %.
  • Unary plus and minus are applied to a single operand.
  • Increment (++) increases a variable by one.
  • Decrement (--) decreases a variable by one.
  • Pre-increment and post-increment differ in the value returned by the expression.
  • Integer division truncates the fractional part toward zero.
  • Use parentheses to clarify the intended order of calculations.
  • Check integer divisors before division and remainder operations.
  • Consider overflow when performing calculations with large numbers.
  • Use BigDecimal when exact decimal arithmetic is required.

23. Conclusion

Arithmetic operators are fundamental to Java programming because they allow developers to calculate totals, differences, products, quotients, remainders, and updated numeric values. Understanding how each operator works, how data types affect results, and how precedence determines evaluation order helps prevent common programming mistakes.

Practice arithmetic expressions with integers and floating-point values, experiment with increment and decrement operators, and write small calculator programs. These skills provide a foundation for more advanced Java topics such as loops, conditional statements, methods, arrays, and object-oriented programming.

To continue learning, explore the Core Java Training Course, visit the JustAcademy website, or register for a course demo.

whatsapp